package com.algo.rpc.server;

import com.algo.rpc.common.RpcDecoderHandler;
import com.algo.rpc.common.RpcEncoderHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;

/**
 * rpc服务端
 */
public class RpcNettySerevr {

    private static final Logger logger = Logger.getLogger(RpcNettySerevr.class);

    private int port = 8888; // 默认端口 8888

    private ServiceRegistry serviceRegistry = ServiceRegistry.getInstance();

    public RpcNettySerevr(int port) {
        this.port = port;
    }

    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(8);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline()
                                    .addLast(new RpcDecoderHandler())
                                    .addLast(new RpcEncoderHandler())
                                    .addLast(new RpcNettyServerHandler(serviceRegistry));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .option(ChannelOption.SO_KEEPALIVE, true);

        try {
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            logger.info("rpc netty server running, listened port is " + port);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("rpc netty server start error, listened port is " + port);
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
